package testview.zhen.com.myapplication.tool;

import android.os.Environment;
import android.util.Log;



import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FileHelper
{
    public static final String SD = Environment.getExternalStorageDirectory().getPath() + "/";
    public static final String DIR = SD + "Controller/";
    public static final String recordDIR = DIR + "Record/";
    public static final String downloadDIR = DIR + "Download/";
    public static final String musicDIR = SD + "Music/";

    static
    {
	File file = new File(DIR);
	file.mkdirs();
	file = new File(recordDIR);
	file.mkdirs();
	file = new File(downloadDIR);
	file.mkdirs();
	file = null;
    }

    public static void write(String content, String name)
    {
	try
	{
	    File file = new File(DIR);
	    file.mkdirs();

	    FileOutputStream fos = new FileOutputStream(file.getPath() + "/" + name, true);
	    fos.write(content.getBytes());
	    fos.close();
	}
	catch (IOException e)
	{
	    e.printStackTrace();
	}
    }

    // 读取文本文件中的内容
    public static synchronized String readTextFile(String path, boolean readLine)
    {
	String content = ""; // 文件内容字符串
	// 打开文件
	File file = new File(path);
	// 如果path是传递过来的参数，可以做一个非目录的判断
	if (file.exists() && !file.isDirectory())
	{
	    try
	    {
		InputStream instream = new FileInputStream(file);
		if (instream != null)
		{
		    InputStreamReader inputreader = new InputStreamReader(instream);
		    BufferedReader buffreader = new BufferedReader(inputreader);
		    String line;
		    // 分行读取
		    while ((line = buffreader.readLine()) != null)
		    {
			content += line;
			if (readLine) content += "\n";
		    }
		    instream.close();
		}
	    }
	    catch (Exception e)
	    {
		Log.d("s","The File doesn't not exist.");
	    }
	}
	return content;
    }

    /**
     * 获取文件夹大小
     * 
     * @param
     *
     * @return long
     */
    public static long getFolderSize(String folder, boolean countFolder)
    {
	return getFolderSize(new File(folder), countFolder);
    }

    public static long getFolderSize(File file, boolean countFolder)
    {
	long size = 0;
	try
	{
	    File[] files = file.listFiles();
	    for (int i = 0; i < files.length; i++)
	    {
		if (files[i].isDirectory())
		{
		    if (!countFolder) continue;
		    size = size + getFolderSize(files[i], countFolder);
		}
		else
		{
		    size = size + files[i].length();
		}
	    }
	}
	catch (Exception e)
	{
	    e.printStackTrace();
	}
	// return size/1048576;
	return size;
    }
}
